import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    user:{},
    socketCollections:[]
    // [{fromws,content[{id:1,content:obj.content}]}]
  },
  getters: {
  },
  mutations: {
    saveuserInfo(state,data){//将用户数据写入仓库
      state.user = data
    },
    setinfofromws(state,obj={}){
      state.socketCollections.map((item,index,array)=>{
        if(item.fromws&&item.fromws.account==obj.fromws.account){
          item.content.push({id:1,content:obj.content})
        }
        if(index + 1 == array.length&&item.fromws.account!==obj.fromws.account){
          array.push({fromws:obj.fromws,content:[{id:1,content:obj.content}]})
        }
        return item
      })
      if(state.socketCollections.length == 0){
        state.socketCollections.push({fromws:obj.fromws,content:[{id:1,content:obj.content}]})
      }
      // state.socketCollections.push(obj)
    }
  },
  actions: {
    saveuserInfoAction({commit},userInfo){//{commit}是context上下文对象中的方法 
      commit('saveuserInfo',userInfo)
    },
    SOCKET_geting({state,commit},data){//websocket服务端接收信息
      console.log('服务端来数据啦:',data);
      if(data.fromws){
        let {fromws,content,timer} = data
        commit('setinfofromws',{fromws,content})
      }
      //拿到数据后再本地缓存中放入该集合，如果这个集合存在那么直接push到collections里去
      
    }
  },
  modules: {
  }
})
